package com.hushao.lims.weblims.service.impl;

import com.hushao.lims.weblims.domain.ConsumableApply;
import com.hushao.lims.weblims.domain.ConsumableOutgoing;
import com.hushao.lims.weblims.domain.ConsumableRepertory;
import com.hushao.lims.weblims.domain.TeacherInfo;
import com.hushao.lims.weblims.repository.ConsumableOutgoingRepository;
import com.hushao.lims.weblims.service.ConsumableApplyService;
import com.hushao.lims.weblims.service.ConsumableOutgoingService;
import com.hushao.lims.weblims.service.ConsumableRepertoryService;
import com.hushao.lims.weblims.util.PersonalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 930588706
 * @date 18/1/22
 */
@Service
public class ConsumableOutgoingServiceImpl implements ConsumableOutgoingService {
    @Autowired
    private ConsumableApplyService consumableApplyService;
    @Autowired
    private ConsumableRepertoryService consumableRepertoryService;
    @Autowired
    private ConsumableOutgoingRepository consumableOutgoingRepository;

    @Autowired
    private PersonalUtil personalUtil;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public ConsumableOutgoing outgoing(ConsumableOutgoing consumableOutgoing) throws Exception {

        //查询耗材申请表中是否有已通过的申请
        List<ConsumableApply> consumableApplies= consumableApplyService.listConsumableAndCountAndState(consumableOutgoing.getConsumableInfo(),consumableOutgoing.getConsumableCount(),"1");
        if(consumableApplies.size()==0){
            throw new Exception("出库失败，没申请此耗材或没通过！");
        }
        TeacherInfo teacherInfo=consumableOutgoing.getRecipients();
        for (ConsumableApply ca:consumableApplies){
            //判断是否是申请人或者申请人给予权限
            boolean  exists=personalUtil.isJurisdiction(ca.getTeacherInfo(),teacherInfo);
            if(exists){
                //修改此申请耗材状态为：已完成(3)
                ca.setApplyConsumableState("3");
                consumableApplyService.update(ca);
                return this.save(consumableOutgoing);
            }
        }
        throw new Exception("出库失败，此人没有权限领取！");
    }




    @Override
    public ConsumableOutgoing save(ConsumableOutgoing consumableOutgoing) throws Exception {
        //查询此耗材库存
        ConsumableRepertory consumableRepertory= consumableRepertoryService.findByConsumable(consumableOutgoing.getConsumableInfo());
        //修改此耗材库存量
        Integer count=consumableRepertory.getConsumableCount()-consumableOutgoing.getConsumableCount();
        consumableRepertory.setConsumableCount(count);
        consumableRepertoryService.saveOrUpdate(consumableRepertory);
        //出库
        return  consumableOutgoingRepository.save(consumableOutgoing);
    }



}
